package top.dark.config;

import com.zaxxer.hikari.HikariDataSource;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.starter.SQLManagerCustomize;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;

/**
 * Author: Lijiao
 * description:
 * Create Time: 2021/5/12 17:47
 */
@Configuration
@EnableTransactionManagement
public class BeetlsqlConfig {

    @Primary
    @Bean(name = "ds1")
    public DataSource datasource() {
        HikariDataSource ds = new HikariDataSource();
        //内存数据库
        ds.setJdbcUrl("jdbc:mysql://localhost:3306/gulimall_bts");
        ds.setUsername("root");
        ds.setPassword("admin");
        ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
        return ds;
    }


    @Bean(name = "ds2")
    public DataSource datasource2() {
        HikariDataSource ds = new HikariDataSource();
        //内存数据库
        ds.setJdbcUrl("jdbc:mysql://localhost:3306/gulimall_pms");
        ds.setUsername("root");
        ds.setPassword("admin");
        ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
        return ds;
    }

    @Bean
    public SQLManagerCustomize mySQLManagerCustomize(){
        return new SQLManagerCustomize() {
            /**
             * @param sqlMangerName  sqlManger的名称，在yml配置文件中的beetlsql:sqlManagers配置
             * @param manager 对应的sqlManager实例
             */
            @Override
            public void customize(String sqlMangerName, SQLManager manager) {
                System.out.println(sqlMangerName + "  sql manager init .....................");
                //初始化sql，这里也可以对sqlManager进行修改
                if (sqlMangerName.equals("sqlManager2")) {
                    //DBInitHelper.executeSqlScript(manager,"db/schema.sql");
                }
            }
        };
    }


    @Bean(name = "btsManagerOne")
    public DataSourceTransactionManager getDataSourceTransactionManagerBts(@Qualifier("ds1") DataSource datasource) {
        DataSourceTransactionManager dsm = new DataSourceTransactionManager();
        dsm.setDataSource(datasource);
        return dsm;
    }

    @Bean(name = "pmsManagerOne")
    public DataSourceTransactionManager getDataSourceTransactionManagerPms(@Qualifier("ds2") DataSource datasource) {
        DataSourceTransactionManager dsm = new DataSourceTransactionManager();
        dsm.setDataSource(datasource);
        return dsm;
    }
}
